<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- plugin.cpp -->
  <title>Qt Quick Local Storage QML Types | Qt Quick 5.11</title>
  <link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
  <script type="text/javascript">
    document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");
    // loading style sheet breaks anchors that were jumped to before
    // so force jumping to anchor again
    setTimeout(function() {
        var anchor = location.hash;
        // need to jump to different anchor first (e.g. none)
        location.hash = "#";
        setTimeout(function() {
            location.hash = anchor;
        }, 0);
    }, 0);
  </script>
</head>
<body>
<div class="header" id="qtdocheader">
  <div class="main">
    <div class="main-rounded">
      <div class="navigationbar">
        <table><tr>
<td ><a href="../qtdoc/index.html">Qt 5.11</a></td><td ><a href="qtquick-index.html">Qt Quick</a></td><td >Qt Quick Local Storage QML Types</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.11.1 参考指南</td>
        </tr></table>
      </div>
    </div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar">
<div class="toc">
<h3><a name="toc">内容</a></h3>
<ul>
<li class="level1"><a href="#methods">函数方法</a></li>
<li class="level1"><a href="#detailed-description">详细描述</a></li>
<li class="level1"><a href="#method-documentation">函数方法文档</a></li>
</ul>
</div>
<div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">Qt Quick Local Storage QML Types</h1>
<span class="subtitle"></span>
<!-- $$$QtQuick.LocalStorage-description -->
<div class="descr"> <a name="details"></a>
<p>这是一个单例类型，用于读取和写入<a href="../qtsql/qtsql-attribution-sqlite.html#sqlite">SQLite</a>数据库。</p>
<a name="methods"></a>
<h2 id="methods">方法</h2>
<ul>
<li>对象<b><a href="qtquick-localstorage-qmlmodule.html#opendatabasesync">openDatabaseSync</a></b>(string name, string version, string description, int estimated_size, jsobject callback(db))</li>
</ul>
<a name="detailed-description"></a>
<h2 id="detailed-description">详细描述</h2>
<p>若要使用本模块中的类型，请导入模块并使用<code>LocalStorage</code>类型调用相关函数</p>
<pre class="cpp">

  import <span class="type">QtQuick</span><span class="operator">.</span>LocalStorage <span class="number">2.0</span>
  import <span class="type">QtQuick</span> <span class="number">2.0</span>

  Item {
      Component<span class="operator">.</span>onCompleted: {
          var db <span class="operator">=</span> LocalStorage<span class="operator">.</span>openDatabaseSync(<span class="operator">.</span><span class="operator">.</span><span class="operator">.</span>)
      }
  }

</pre>
<p>这些数据库是特定于用户和特定于QML的，但是可以访问所有QML应用程序。他们被存储在<a href="../qtqml/qqmlengine.html#offlineStoragePath-prop">QQmlEngine::offlineStoragePath</a>()的<code>Databases</code>的子目录中，当前为<a href="../qtsql/qtsql-attribution-sqlite.html#sqlite">SQLite</a>数据库。</p>
<p>数据库连接在Javascript垃圾收集期间自动关闭。</p>
<p>该API允许在您的QML中使用JavaScript</p>
<pre class="qml">

  import QtQuick 2.0

  <span class="type"><a href="qml-qtquick-rectangle.html">Rectangle</a></span> {
      <span class="name">color</span>: <span class="string">&quot;white&quot;</span>
      <span class="name">width</span>: <span class="number">200</span>
      <span class="name">height</span>: <span class="number">100</span>

      <span class="type"><a href="qml-qtquick-text.html">Text</a></span> {
          <span class="name">text</span>: <span class="string">&quot;?&quot;</span>
          <span class="name">anchors</span>.horizontalCenter: <span class="name">parent</span>.<span class="name">horizontalCenter</span>
          <span class="keyword">function</span> <span class="name">findGreetings</span>() {
              var <span class="name">db</span> = <span class="name">openDatabaseSync</span>(<span class="string">&quot;QDeclarativeExampleDB&quot;</span>, <span class="string">&quot;1.0&quot;</span>, <span class="string">&quot;The Example QML SQL!&quot;</span>, <span class="number">1000000</span>);

              <span class="name">db</span>.<span class="name">transaction</span>(
                  <span class="keyword">function</span>(<span class="name">tx</span>) {
                      <span class="comment">// Create the database if it doesn't already exist</span>
                      <span class="name">tx</span>.<span class="name">executeSql</span>(<span class="string">'CREATE TABLE IF NOT EXISTS Greeting(salutation TEXT, salutee TEXT)'</span>);

                      <span class="comment">// Add (another) greeting row</span>
                      <span class="name">tx</span>.<span class="name">executeSql</span>(<span class="string">'INSERT INTO Greeting VALUES(?, ?)'</span>, [ <span class="string">'hello'</span>, <span class="string">'world'</span> ]);

                      <span class="comment">// Show all added greetings</span>
                      var <span class="name">rs</span> = <span class="name">tx</span>.<span class="name">executeSql</span>(<span class="string">'SELECT * FROM Greeting'</span>);

                      var <span class="name">r</span> = <span class="string">&quot;&quot;</span>
                      <span class="keyword">for</span> (<span class="keyword">var</span> <span class="name">i</span> = <span class="number">0</span>; <span class="name">i</span> <span class="operator">&lt;</span> <span class="name">rs</span>.<span class="name">rows</span>.<span class="name">length</span>; i++) {
                          <span class="name">r</span> <span class="operator">+=</span> <span class="name">rs</span>.<span class="name">rows</span>.<span class="name">item</span>(<span class="name">i</span>).<span class="name">salutation</span> <span class="operator">+</span> <span class="string">&quot;, &quot;</span> <span class="operator">+</span> <span class="name">rs</span>.<span class="name">rows</span>.<span class="name">item</span>(<span class="name">i</span>).<span class="name">salutee</span> <span class="operator">+</span> <span class="string">&quot;\n&quot;</span>
                      }
                      <span class="name">text</span> <span class="operator">=</span> <span class="name">r</span>
                  }
              )
          }
          <span class="name">Component</span>.onCompleted: <span class="name">findGreetings</span>()
      }
  }

</pre>
<p>该API符合HTML5 Web数据库API的同步API, <a href="http://www.w3.org/TR/2009/WD-webdatabase-20091029/">W3C 2009年10月29日工作草案。</a>.</p>
<p><a href="qtquick-localstorage-example.html">SQL本地存储示例</a>演示了使用离线存储API的基础知识。</p>
<a name="open-or-create-a-database"></a>
<h4 >打开或创建数据库</h4>
<pre class="cpp">

  import <span class="type">QtQuick</span><span class="operator">.</span>LocalStorage <span class="number">2.0</span> as Sql

  db <span class="operator">=</span> Sql<span class="operator">.</span>openDatabaseSync(identifier<span class="operator">,</span> version<span class="operator">,</span> description<span class="operator">,</span> estimated_size<span class="operator">,</span> callback(db))

</pre>
<p>上面的代码返回由<i>identifier（标识符）</i>标识的数据库。如果数据库还不存在，就创建它，并使用数据库作为参数调用函数<i>回调</i>。<i>identifier（标识符）</i>是包含数据库的物理文件的名称(包含或不包含完整路径)。<i>description</i>和<i>estimated_size</i> 被写入INI文件(如下所述)，但目前未使用。</p>
<p>代码属性 SQLException.DATABASE_ERR 或 SQLException.VERSION_ERR 可能引发异常。</p>
<p>当第一次创建数据库时，还会创建一个INI文件，指定它的特性:</p>
<div class="table"><table class="generic">
 <thead><tr class="qt-style"><th ><b>键</b></th><th ><b>值</b></th></tr></thead>
<tr valign="top" class="odd"><td >Identifier</td><td >一个传给<code>openDatabase()</code>的数据库名字</td></tr>
<tr valign="top" class="even"><td >Version</td><td >一个传给<code>openDatabase()</code>的数据库版本</td></tr>
<tr valign="top" class="odd"><td >Description</td><td >一个传给<code>openDatabase()</code>的数据库的描述</td></tr>
<tr valign="top" class="even"><td >EstimatedSize</td><td >传递给<code>openDatabase()</code>的数据库的估计大小(以字节为单位)</td></tr>
<tr valign="top" class="odd"><td >Driver</td><td >当前的&quot;QSQLITE&quot;</td></tr>
</table></div>
<p>应用程序工具可以使用这些数据。</p>
<a name="db-changeversion-from-to-callback-tx"></a>
<h4 >db.changeVersion(from, to, callback(tx))</h4>
<p>此方法允许您执行<i>Scheme Upgrade</i>。</p>
<p>如果当前版本的<i>db</i>不<i>来自</i>, 则抛出异常。</p>
<p>否则，将创建数据库事务并将其传递给<i>回调</i>。在这个函数中，您可以用<i>tx</i>调用<i>executeSql</i>去更新数据库。</p>
<p>代码属性 SQLException.DATABASE_ERR 或 SQLException.UNKNOWN_ERR 可能引发异常。</p>
<p>请参见如下例子：</p>
<pre class="cpp plain">

  var db = LocalStorage.openDatabaseSync(&quot;ActivityTrackDB&quot;, &quot;&quot;, &quot;Database tracking sports activities&quot;, 1000000);
  if (db.version == &quot;0.1&quot;) {
      db.changeVersion(&quot;0.1&quot;, &quot;0.2&quot;, function(tx) {
          tx.executeSql(&quot;INSERT INTO trip_log VALUES(?, ?, ?)&quot;,
                      [ &quot;01/10/2016&quot;,&quot;Sylling - Vikersund&quot;, &quot;53&quot; ]);
      }
  });

</pre>
<a name="db-transaction-callback-tx"></a>
<h4 >db.transaction(callback(tx))</h4>
<p>此方法创建一个读/写事务并传递给<i>回调</i>。。在这个函数中，您可以使用<i>tx</i>调用executeSql<i>executeSql</i>来读取和修改数据库。</p>
<p>如果回调引发异常，则回滚事务。下面是捕获异常的数据库事务示例。</p>
<pre class="cpp">

  {
      var <span class="name">db</span> = <span class="name">LocalStorage</span>.<span class="name">openDatabaseSync</span>(<span class="string">&quot;Activity_Tracker_DB&quot;</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;Track exercise&quot;</span>, <span class="number">1000000</span>)
      <span class="keyword">try</span> {
          <span class="name">db</span>.<span class="name">transaction</span>(<span class="keyword">function</span> (<span class="name">tx</span>) {
              <span class="name">tx</span>.<span class="name">executeSql</span>(<span class="string">'CREATE TABLE IF NOT EXISTS trip_log (date text,trip_desc text,distance numeric)'</span>)
          })
      } <span class="keyword">catch</span> (<span class="name">err</span>) {
          console.log(&quot;Error creating table in database: &quot; + err)
      };
  }

</pre>
<p>在本例中，您可以看到一条<code>insert</code>语句，其中值被分配给字段，记录被写入表中。这是一个<code>insert</code>语句，其语法与关系数据库中常用的语法相同。不过，也可以使用JSON对象并将它们存储在表中。</p>
<p>让我们假设一个简单的示例，其中我们使用<code>date</code>作为惟一键以JSON格式存储访问。可用于此目的的一个表的例子:</p>
<pre class="cpp plain">

  create table trip_log(date text, data text)

</pre>
<p>赋值给JSON对象:</p>
<pre class="cpp plain">

  var obj = {description = &quot;Vikersund - Noresund&quot;, distance = &quot;60&quot;}

</pre>
<p>在这种情况下，数据可以通过以下方式保存:</p>
<pre class="cpp plain">

  db.transaction(function(tx) {
      result = tx.executeSQL(&quot;insert into trip_log values (?,?)&quot;,
                             [&quot;01/11/2016&quot;, JSON.stringify(obj)])

</pre>
<a name="db-readtransaction-callback-tx"></a>
<h4 >db.readTransaction(callback(tx))</h4>
<p>此方法创建只读事务并传递给<i>回调</i>。在这个函数中，您可以使用<i>tx</i>调用<i>executeSql</i>来读取数据库(使用 <code>select</code> 语句)。</p>
<a name="results-tx-executesql-statement-values"></a>
<h4 >results = tx.executeSql(statement, values)</h4>
<p>此方法执行SQL <i>语句</i>，绑定<i>值</i>列表到一个SQL位置参数(&quot;?&quot;)中。</p>
<p>It returns a results object, with the following properties:</p>
<div class="table"><table class="generic">
 <thead><tr class="qt-style"><th ><b>类型</b></th><th ><b>属性</b></th><th ><b>值</b></th><th ><b>使用</b></th></tr></thead>
<tr valign="top" class="odd"><td >int</td><td >rows.length</td><td >结果中的行数</td><td >SELECT</td></tr>
<tr valign="top" class="even"><td >var</td><td >rows.item(i)</td><td >函数返回结果的第<i>i</i>行</td><td >SELECT</td></tr>
<tr valign="top" class="odd"><td >int</td><td >rowsAffected</td><td >受修改影响的行数</td><td >UPDATE, DELETE</td></tr>
<tr valign="top" class="even"><td >string</td><td >insertId</td><td >插入行的id</td><td >INSERT</td></tr>
</table></div>
<p>代码 SQLException.DATABASE_ERR，SQLException.SYNTAX_ERR 或 SQLException.UNKNOWN_ERR 可能引发异常。</p>
<p>请看以下示例：</p>
<pre class="cpp">

  <span class="keyword">function</span> <span class="name">dbReadAll</span>()
  {
      var <span class="name">db</span> = <span class="name">dbGetHandle</span>()
      <span class="name">db</span>.<span class="name">transaction</span>(<span class="keyword">function</span> (<span class="name">tx</span>) {
          var <span class="name">results</span> = <span class="name">tx</span>.<span class="name">executeSql</span>(
                      <span class="string">'SELECT rowid,date,trip_desc,distance FROM trip_log order by rowid desc'</span>)
          <span class="keyword">for</span> (<span class="keyword">var</span> <span class="name">i</span> = <span class="number">0</span>; <span class="name">i</span> <span class="operator">&lt;</span> <span class="name">results</span>.<span class="name">rows</span>.<span class="name">length</span>; i++) {
              <span class="name">listModel</span>.<span class="name">append</span>({
                                   id: <span class="name">results</span>.<span class="name">rows</span>.<span class="name">item</span>(<span class="name">i</span>).<span class="name">rowid</span>,
                                   checked: <span class="string">&quot; &quot;</span>,
                                   date: <span class="name">results</span>.<span class="name">rows</span>.<span class="name">item</span>(<span class="name">i</span>).<span class="name">date</span>,
                                   trip_desc: <span class="name">results</span>.<span class="name">rows</span>.<span class="name">item</span>(<span class="name">i</span>).<span class="name">trip_desc</span>,
                                   distance: <span class="name">results</span>.<span class="name">rows</span>.<span class="name">item</span>(<span class="name">i</span>).<span class="name">distance</span>
                               })
          }
      })
  }

</pre>
<a name="method-documentation"></a>
<h2 id="method-documentation">函数方法文档</h2>
<a name="opendatabasesync"></a><pre class="cpp">

  object openDatabaseSync(string name<span class="operator">,</span> string version<span class="operator">,</span> string description<span class="operator">,</span> <span class="type"><a href="../qtqml/qml-int.html">int</a></span> estimated_size<span class="operator">,</span> jsobject callback(db))

</pre>
<p>根据给定的参数打开或创建本地存储sql数据库。</p>
<ul>
<li><code>name</code>是数据库名称</li>
<li><code>version</code>是数据库版本</li>
<li><code>description</code>是数据库显示名称</li>
<li><code>estimated_size</code>是数据库的估计大小，以字节为单位</li>
<li><code>callback</code>调是一个可选参数，如果尚未创建数据库，将调用该参数。</li>
</ul>
<p>返回创建的数据库对象。</p>
</div>
<!-- @@@QtQuick.LocalStorage -->
        </div>
       </div>
   </div>
   </div>
</div>
<div class="footer">
   <p>
   <acronym title="Copyright">&copy;</acronym> 2018 The Qt Company Ltd.
   Documentation contributions included herein are the copyrights of
   their respective owners.<br>    The documentation provided herein is licensed under the terms of the    <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation    License version 1.3</a> as published by the Free Software Foundation.<br>    Qt and respective logos are trademarks of The Qt Company Ltd.     in Finland and/or other countries worldwide. All other trademarks are property
   of their respective owners. </p>
</div>
</body>
</html>
